package dav

import (
	"tosServer/internal/model"
	"tosServer/internal/pkg/common"
	"tosServer/internal/pkg/db"

	"github.com/gin-gonic/gin"
)

// GetUserRoleInfo
// @Summary 获取dav角色信息
// @Tags	dav
// @Param	request body model.IdToWhere true "request"
// @Success	200  {object}  common.R
// @Router	/dav/get_user_role_info [post]
func (d *Dav) GetUserRoleInfo(c *gin.Context) {
	params := new(model.IdToWhere)
	err := c.ShouldBind(params)
	if err != nil {
		d.Api.Error(c, &common.R{
			Msg: err.Error(),
		})
		return
	}

	davUserRole := new(model.DavUserRole)
	result := db.Db().Table(model.TableNameDavUserRole).Where(params).First(&davUserRole)

	if result.Error != nil {
		d.Api.Error(c, &common.R{
			Msg: result.Error.Error(),
		})
		return
	}

	d.Api.Success(c, &common.R{
		Data: davUserRole,
	})

}

// CreateUserRole
// @Summary 创建dav账号角色
// @Tags	dav
// @Param	request body model.CreateDavUserRole true "request"
// @Success	200  {object}  common.R
// @Router	/dav/create_user_role [post]
func (d *Dav) CreateUserRole(c *gin.Context) {

	createDavUserRole := new(model.CreateDavUserRole)
	err := c.ShouldBind(createDavUserRole)
	if err != nil {
		d.Api.Error(c, &common.R{
			Msg: err.Error(),
		})
		return
	}

	davUserRole := new(model.DavUserRole)
	davUserRole.Name = createDavUserRole.Name
	davUserRole.Methods = createDavUserRole.Methods
	davUserRole.Path = createDavUserRole.Path
	result := db.Db().Table(model.TableNameDavUserRole).Create(&davUserRole)

	if result.Error != nil {
		d.Api.Error(c, &common.R{
			Msg: result.Error.Error(),
		})
		return
	}

	d.Api.Success(c, &common.R{
		Data: davUserRole,
	})

}

// UpdateUserRole
// @Summary 更新dav账号角色
// @Tags	dav
// @Param	request body model.UpdateDavUserRole true "request"
// @Success	200  {object}  common.R
// @Router	/dav/update_user_role [post]
func (d *Dav) UpdateUserRole(c *gin.Context) {
	updateDavUserRole := new(model.UpdateDavUserRole)
	err := c.ShouldBind(updateDavUserRole)
	if err != nil {
		d.Api.Error(c, &common.R{
			Msg: err.Error(),
		})
		return
	}
	davUserRole := new(model.DavUserRole)
	if updateDavUserRole.Name != "" {
		davUserRole.Name = updateDavUserRole.Name
	}
	if updateDavUserRole.Path != "" {
		davUserRole.Path = updateDavUserRole.Path
	}
	if updateDavUserRole.Methods != "" {
		davUserRole.Methods = updateDavUserRole.Methods
	}

	result := db.Db().Table(model.TableNameDavUserRole).Where("id", updateDavUserRole.ID).Updates(&davUserRole)

	if result.Error != nil {
		d.Api.Error(c, &common.R{
			Msg: result.Error.Error(),
		})
		return
	}

	d.Api.Success(c, &common.R{})

}
